package io.BIO;

import java.io.*;

/**
 * @author 26029
 * @date 2025/4/18
 * @description
 */
public class LearnBIO {
    public static void main(String[] args) {
        // BIO:使用FileInputStream和FileOutputStream, fis.read()和fos.write()会阻塞进程

        String file_path = "D:\\project\\learnJava\\src\\main\\java\\io\\BIO\\test.txt";
        String copy_path1 = "D:\\project\\learnJava\\src\\main\\java\\io\\BIO\\test_copy1.txt";
        String copy_path2 = "D:\\project\\learnJava\\src\\main\\java\\io\\BIO\\test_copy2.txt";
        String copy_path3 = "D:\\project\\learnJava\\src\\main\\java\\io\\BIO\\test_copy3.txt";
        String copy_path4 = "D:\\project\\learnJava\\src\\main\\java\\io\\BIO\\test_copy4.txt";

        //使用 jdk7 引入的自动关闭资源的 try 语句（该资源类要实现 AutoCloseable 或 Closeable 接口）

        // 字节流
        try (FileInputStream fis = new FileInputStream(file_path);
             FileOutputStream fos = new FileOutputStream(copy_path1)
        ) {
            byte[] buf = new byte[126];
            int hasRead = 0; // 每次读到的数量
            while ((hasRead = fis.read(buf)) > 0) {
                fos.write(buf, 0, hasRead); //每次读取多少就写多少
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 字符流
        try (FileReader fr = new FileReader(file_path);
             FileWriter fw = new FileWriter(copy_path2)
        ) {
            char[] buf = new char[4];
            int hasRead = 0;
            while ((hasRead = fr.read(buf)) > 0)
                fw.write(buf, 0, hasRead);
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 字符流:整行读取
        try (FileReader fr = new FileReader(file_path);
             FileWriter fw = new FileWriter(copy_path3);
             BufferedReader br = new BufferedReader(fr);
             BufferedWriter bw = new BufferedWriter(fw)
        ){
            String line;
            while ((line = br.readLine()) != null) {
                bw.write(line);
                bw.newLine();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 随机读写:可以定位文件位置,可以同时支持读和写
        try (RandomAccessFile in = new RandomAccessFile(file_path, "rw");
             RandomAccessFile out = new RandomAccessFile(copy_path4, "rw")
        ){
            byte[] buf = new byte[2];
            int hasRead = 0;
            while ((hasRead = in.read(buf)) > 0)
                out.write(buf, 0, hasRead);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
